// useHtmlToImage.js
import { ref } from 'vue';

const useHtmlToImage = (selector, filename = 'converted-image.png') => {
  const isConverting = ref(false);
  const error = ref(null);

  const convertToImage = async () => {
    try {
      isConverting.value = true;
      const node = document.querySelector(selector);

      if (!node) {
        throw new Error(`Element with selector ${selector} not found`);
      }

      // 将所有的 <input> 元素转换为 <div> 元素
      const inputs = node.querySelectorAll('input');
      inputs.forEach(input => {
        const div = document.createElement('div');
        div.className = input.className; // 复制类名

        // 获取计算后的样式
        const computedStyle = window.getComputedStyle(input);
        for (let prop of computedStyle) {
          div.style[prop] = computedStyle[prop];
        }

        div.textContent = input.value; // 复制输入值
        input.parentNode.replaceChild(div, input);
      });

      // 确保动态样式已经应用
      await new Promise(resolve => requestAnimationFrame(() => {
        requestAnimationFrame(resolve);
      }));

      const canvas = await html2canvas(node, {
        allowTaint: true,
        useCORS: true,
        logging: true,
        scale: window.devicePixelRatio || 1
      });

      return new Promise((resolve, reject) => {
        canvas.toBlob((blob) => {
          isConverting.value = false;
          resolve(blob);
        }, 'image/png');
      });
    } catch (err) {
      error.value = err;
      isConverting.value = false;
      return null;
    }
  };

  return { isConverting, error, convertToImage };
};

export default useHtmlToImage;